import { Box, Typography, Chip, Stack } from "@mui/material";
import { gql, useQuery, useMutation } from "@apollo/client";
import { initializeApollo } from "lib/apollo";
import Loading from "components/Loading";
import { useRouter } from "next/router";
import toast from "react-hot-toast";
import BaseWrap from "components/BaseWrap";
import PostContent from "components/Post/PostContent";
import PostComments from "components/Post/PostComments";

const POST_BY_ID = gql`
  query Query($post_id: Int!) {
    postById(id: $post_id) {
      id
      authorId
      title
      description
      content
      createdAt
      updatedAt
      url
      thumbnail
      isLocked
      viewCount
      likesCount
      isLiked
      forum {
        title
        id
        category {
          name
        }
      }
      author {
        name
        id
        image
      }
      tags {
        id
        name
        description
      }
      comments {
        id
        content
        createdAt
        user {
          name
          image
          email
        }
        reviews {
          id
          content
          createdAt
          user {
            name
            email
            image
          }
        }
      }
    }
  }
`;

export async function getServerSideProps({ query: { id } }) {
  const {
    data: { postById },
  } = await initializeApollo().query({
    query: POST_BY_ID,
    variables: {
      post_id: Number(id),
    },
  });

  if (!postById)
    return {
      redirect: {
        destination: "/404",
        permanent: false,
      },
    };
  return {
    props: { data: { ...postById } },
  };
}

export default function Posts({ data }) {
  const router = useRouter();
  if (!data) if (router.isFallback) return <Loading />;
  return (
    <BaseWrap title={data.title}>
      <PostContent data={data} />
      <PostComments {...{ comments: data.comments, id: data.id }} />
    </BaseWrap>
  );
}
